﻿using Helpers;
using MarriageFertility.Extensions;
using MarriageFertility.Helpers;
using MarriageFertility.Missions;
using MarriageFertility.Texts;
using SandBox;
using SandBox.Missions.MissionLogics;
using SandBox.Missions.MissionLogics.Arena;
using TaleWorlds.CampaignSystem;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.GameMenus;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.CampaignSystem.Settlements.Locations;
using TaleWorlds.Localization;
using TaleWorlds.MountAndBlade;
using TaleWorlds.MountAndBlade.Source.Missions;
using TaleWorlds.MountAndBlade.Source.Missions.Handlers;

namespace MarriageFertility.Behaviors
{
    public class SpouseTournamentBehavior : CampaignBehaviorBase
    {
        private const int TournamentCost = 10000; 

        public override void RegisterEvents()
        {
            CampaignEvents.OnSessionLaunchedEvent.AddNonSerializedListener(this, OnSessionLaunched);
        }

        public override void SyncData(IDataStore dataStore)
        {
            // 暂无数据需要同步
        }

        private void OnSessionLaunched(CampaignGameStarter campaignGameStarter)
        {
            GameMenuHelper gameMenuHelper = new GameMenuHelper(campaignGameStarter);

            // 添加进入正官选拔赛选项
            gameMenuHelper.AddBasicOption("town_arena", "town_spouse_tournament", 
                TournamentText.HostTournamentOption.ToString(), GameMenuOption.LeaveType.Continue, delegate
                {
                    GameMenu.SwitchToMenu("ad_menu_mf_tournament");
                }, 0);

            // 设置正官选拔赛菜单
            gameMenuHelper.Add("ad_menu_mf_tournament", TournamentText.TournamentDescription);

            // 添加比赛开始选项
            gameMenuHelper.AddConditionOption(
                "ad_menu_mf_tournament", 
                "fight", 
                TournamentText.StartTournamentOption.ToString(), 
                GameMenuOption.LeaveType.HostileAction, 
                TournamentCondition, 
                TournamentConsequence);

            // 添加返回选项
            gameMenuHelper.AddResumeOption("ad_menu_mf_tournament", "town_arena");
        }
        
        private void TournamentConsequence(MenuCallbackArgs args)
        {
            // 扣除玩家金币并返回竞技场
            GiveGoldAction.ApplyForCharacterToSettlement(Hero.MainHero, Settlement.CurrentSettlement, TournamentCost);
            GameMenu.SwitchToMenu("town_arena");
            CreateNewMission();
        }
        
        private bool TournamentCondition(MenuCallbackArgs args)
        {
            
            int goldShortfall = TournamentCost - Hero.MainHero.Gold; // 计算金币差额
            bool hasEnoughGold = Hero.MainHero.Gold >= TournamentCost; // 判断玩家是否有足够金币
            bool hasEnoughSpouses = Hero.MainHero.SpousesInParty().Count > 2;
            
            // 设置选项状态
            TextObject disabledText=new TextObject(); 
            if (!hasEnoughGold) disabledText = TournamentText.NotEnoughGoldText;
            if (!hasEnoughSpouses) disabledText = TournamentText.NotEnoughSpouseText;
            MBTextManager.SetTextVariable("AD_Extra_Cost", goldShortfall);
            return MenuHelper.SetOptionProperties(args, hasEnoughGold && hasEnoughSpouses, !hasEnoughGold || !hasEnoughSpouses, disabledText);
        }
        
        private void CreateNewMission()
        {
            int upgradeLevel = Settlement.CurrentSettlement.IsTown ? Settlement.CurrentSettlement.Town.GetWallLevel() : 1;
            var missions = new MissionBehavior[]
            {
                new MissionOptionsComponent(),
                new MissionFacialAnimationHandler(),
                new AgentVictoryLogic(),
                new AgentHumanAILogic(),
                new ArenaAgentStateDeciderLogic(),
                new VisualTrackerMissionBehavior(),
                new CampaignMissionComponent(),
                new SpouseBattleMissionMissionLogic(),
                new MissionAgentHandler(LocationComplex.Current.GetLocationWithId("arena"), null)
            };
            MissionState.OpenNew("ArenaDuelMission", SandBoxMissions.CreateSandBoxMissionInitializerRecord(LocationComplex.Current.GetLocationWithId("arena").GetSceneName(upgradeLevel), "", false, 0), (Mission mission) => missions);
        }
    }
}